<template>
  <div class="goodsindex">
    <!-- 搜索条件 -->
    <el-row :gutter="20" class="goodsindex-queryInfo">
      <el-col :xs="8" :sm="5" :md="5" :lg="5" :xl="5">
        <el-input
          class="goodsindex-queryInfo-li"
          v-model="queryInfo.code"
          clearable
          size="small"
          placeholder="请输入产品序号"
        ></el-input>
      </el-col>
      <el-col :xs="6" :sm="4" :md="3" :lg="2" :xl="2">
        <el-button
          type="primary"
          class="goodsindex-queryInfo-li"
          size="small"
          @click="select"
          >搜索</el-button
        >
      </el-col>
      <el-col :xs="6" :sm="4" :md="3" :lg="2" :xl="2">
        <el-button
          class="goodsindex-queryInfo-li"
          type="primary"
          size="small"
          v-if="isAuth('sys:modelList:save')"
          @click="handleAdd()"
          >添加</el-button
        >
      </el-col>
      <el-col :xs="6" :sm="4" :md="3" :lg="2" :xl="2">
        <el-button
          class="goodsindex-queryInfo-li"
          size="small"
          type="danger"
          v-if="isAuth('sys:modelList:delete')"
          @click="handleDelete()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-col>
      <el-col :xs="6" :sm="4" :md="3" :lg="3" :xl="2">
        <el-button
          class="goodsindex-queryInfo-li"
          size="small"
          type="primary"
          v-if="isAuth('sys:modelList:ProjectDriver')"
          @click="handleProjectDriverI()"
          :disabled="dataProjectDriverI.length <= 0"
          >批量关联项目</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="userList"
      border
      size="mini"
      @selection-change="selectionChangeHandle"
      :row-key="getRowID"
      style="width: 100%"
      ref="dataTable"
      :height="tableMaxHeight"
      v-loading="isloading"
    >
      <el-table-column
        type="index"
        header-align="center"
        align="center"
        label="序"
        width="50"
      >
      </el-table-column>
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="code"
        header-align="center"
        align="center"
        label="产品序号"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="model"
        header-align="center"
        align="center"
        label="型号"
      >
      </el-table-column>
      <el-table-column
        prop="ratedCurrent"
        header-align="center"
        align="center"
        label="额定电流"
      >
      </el-table-column>
      <el-table-column
        prop="ratedVoltage"
        header-align="center"
        align="center"
        label="额定电压"
      >
      </el-table-column>
      <el-table-column
        prop="standard"
        header-align="center"
        align="center"
        label="执行标准"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        label="产品类型"
      >
      </el-table-column>
      <el-table-column
        prop="activateState"
        header-align="center"
        align="center"
        label="激活状态"
      >
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.activateState == 0"
            >未激活</el-tag
          >
          <el-tag v-if="scope.row.activateState == 1">已激活</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        width="400"
        prop="address"
        header-align="center"
        align="center"
        fixed="right"
        label="操作"
        v-if="showOrHide"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-if="isAuth('sys:modelList:look')"
            @click="handleLook(scope.row.id)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="primary"
            v-if="isAuth('sys:modelList:update')"
            @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            :type="scope.row.projectId ? 'success' : 'primary'"
            v-if="isAuth('sys:modelList:ProjectDriver')"
            @click="handleProjectDriver(scope.row.id)"
            >关联项目</el-button
          >
          <!-- <el-button size="mini" type="primary" v-if="scope.row.activateState == 1&&isAuth('sys:modelList:activateState')" @click="handleActivation(scope.row.id)">激活详情</el-button> -->
          <!-- <el-popover placement="right" width="400" height="300" trigger="click">
            <vue-qr :text="scope.row.id.toString()" :size="300" style="margin: auto;"></vue-qr>
            <el-button size="mini" type="primary" slot="reference" style="margin-left: 10px" v-if="isAuth('sys:modelList:qrcode')"
              >二维码</el-button>
          </el-popover> -->
          <el-button
            size="mini"
            type="primary"
            style="margin-left: 10px"
            v-if="isAuth('sys:modelList:qrcode')"
            @click="handleQrcode(scope.row.id, scope.row.code)"
            >二维码</el-button
          >

          <el-button
            size="mini"
            type="danger"
            style="margin-left: 10px"
            v-if="isAuth('sys:modelList:delete')"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row :gutter="20" class="goodsindex-list">
      <el-col :span="24" class="goodsindex-page-box">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[1, 2, 10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <add v-if="addVisible" ref="add" @getUserlist="getUserlist"></add>
    <addElDialog
      v-if="userAddorUpdataVisible"
      ref="addElDialog"
      @getUserlist="getUserlist"
    ></addElDialog>
    <updateProject
      v-if="updateProjectVisible"
      ref="updateProject"
      @getUserlist="getUserlist"
    ></updateProject>
    <updateProjectes
      v-if="updateProjectesVisible"
      ref="updateProjectes"
      @getUserlist="getUserlist"
    ></updateProjectes>
    <look v-if="lookVisible" ref="look" @getUserlist="getUserlist"></look>
    <activation
      v-if="activationVisible"
      ref="activation"
      @getUserlist="getUserlist"
    ></activation>
    <el-dialog title="二维码" :visible.sync="qrcodeDialogVisible" width="600px">
      <div style="display: flex">
        <!-- <vue-qr :text="codeText" ref="qrcode" :size="300" :logoSrc="lgoImg" :logoScale="0.2" :logoMargin="0" style="margin: auto;"></vue-qr> -->
        <div style="margin-right: 10px; position: relative">
          <div
            style="
              border: 1px solid #ccc;
              border-radius: 10px;
              padding-top: 5px;
            "
          >
            <vue-qr
              :text="codeText"
              ref="qrcode"
              :size="300"
              style="margin: auto"
            ></vue-qr>
            <div
              style="text-align: center; margin-bottom: 10px; font-size: 18px"
            >
              {{ this.codeQr }}
            </div>
            <div class="qrcodesize">
              <!-- <vue-qr :text="codeText" ref="qrcode2" :margin="0" :size="exitWidth"></vue-qr>
              <p style="text-align: center;font-size: 12px;">{{ codeQr }}</p> -->
              <canvas
                :width="exitWidth"
                :height="exitWidth"
                class="canvas"
                ref="canvas"
              ></canvas>
            </div>
          </div>
        </div>
        <div>
          <el-form
            :model="formSize"
            ref="formSize"
            label-position="top"
            class="demo-ruleForm"
          >
            <el-form-item label="下载尺寸：" prop="size">
              <el-radio-group
                v-model="formSize.size"
                class="qrRadio"
                @change="onSubmit"
              >
                <el-radio label="1" style="width: 100%">2cm x 2cm</el-radio>
                <el-radio label="2" style="width: 100%">3cm x 3cm</el-radio>
                <el-radio label="3" style="width: 100%">4cm x 4cm</el-radio>
                <el-radio label="4" style="width: 100%">5cm x 5cm</el-radio>
                <el-radio label="5" style="width: 100%">自定义尺寸</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="formSize.size == 5" label="自定义：">
              <el-input
                v-model="formSize.custom"
                type="number"
                style="margin-right: 15px"
                @blur="onSubmit"
              />
              <span style="color: #999; font-size: 12px"
                >（最大可设为35cm,最小可设为1cm）</span
              >
            </el-form-item>
          </el-form>
          <el-button
            icon="el-icon-download"
            :disabled="formSize.size == 5 && formSize.custom == ''"
            @click="qrcodeClick(1)"
            >二维码下载</el-button
          >
          <div style="margin-top: 10px">
            <el-button
              icon="el-icon-download"
              :disabled="formSize.size == 5 && formSize.custom == ''"
              @click="qrcodeClick(2)"
              >产品序号_二维码下载</el-button
            >
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qrcodeDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addElDialog from "./addorupdate.vue";
import add from "./add.vue";
import updateProjectes from "./updateProjectes.vue";
import look from "./look.vue";
import updateProject from "./updateProject.vue";
import activation from "./activation.vue";
import VueQr from "vue-qr";
import QRCode from "qrcode";
export default {
  components: {
    addElDialog,
    updateProjectes,
    updateProject,
    look,
    activation,
    VueQr,
    add,
  },
  data() {
    return {
      isShowOrHide: true,
      userAddorUpdataVisible: false, //新增 修改
      addVisible: false, //新增
      updateProjectVisible: false,
      updateProjectesVisible: false,
      qrcodeDialogVisible: false,
      lookVisible: false,
      activationVisible: false,
      queryInfo: {
        code: "",
      },
      formSize: {
        size: "2",
        custom: 2,
      },
      exitWidth: 84,
      userList: [],
      dataListSelections: [], //批量删除
      dataProjectDriverI: [], //关联项目-司机
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      isloading: false,
      codeText: "Hello world!",
      qrBack: "",
      lgoImg: require("../../assets/qrcode.png"),
      codeQr: "",
      firstId: "",
    };
  },
  computed: {
    showOrHide() {
      // if(this.isAuth('')==false&&this.isAuth('')==false&&this.isAuth('')==false){
      //     this.isShowOrHide=false;
      // }
      return true;
    },
    tableMaxHeight() {
      return window.innerHeight - 180 + "px";
    },
  },
  created() {
    this.getUserlist();
  },
  methods: {
    //搜素
    async select() {
      this.pageIndex = 1;
      await this.getUserlist();
    },
    //获取用户列表
    async getUserlist() {
      this.isloading = true;
      this.userList = [];
      this.codeQr = "";
      this.firstId = "";
      await this.Sevice({
        url: "product/list",
        method: "get",
        params: {
          code: this.queryInfo.code,
        },
      })
        .then((res) => {
          // console.log(res)
          if (res && res.code == 200) {
            this.userList = res.list;
            this.firstId = this.userList[0].id;
            this.totalPage = res.list.length;
            this.userList = this.userList.slice(
              (this.pageIndex - 1) * this.pageSize,
              this.pageIndex * this.pageSize
            );
          } else {
            this.userList = [];
            this.totalPage = 0;
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.isloading = false;
    },
    //新增
    handleAdd() {
      this.addVisible = true;
      this.$nextTick(() => {
        this.$refs.add.init(this.firstId);
      });
    },
    //修改
    handleEdit(id) {
      this.userAddorUpdataVisible = true;
      this.$nextTick(() => {
        this.$refs.addElDialog.init(id);
      });
    },
    handleClose(done) {
      done();
    },
    //查看
    add(id) {
      this.$refs.addElDialog.init(id);
    },
    success(data) {
      console.log(data);
    },
    // 多选
    selectionChangeHandle(rows) {
      this.dataListSelections = rows;
      this.dataProjectDriverI = rows;
    },
    getRowID(row) {
      return row.id;
    },
    // size大小
    onSubmit() {
      this.newqrtitlename = "";
      if (this.formSize.size === "1") {
        // this.exitTitle = "20mm x 20mm";
        this.exitWidth = 2 * 28;
      } else if (this.formSize.size === "2") {
        // this.exitTitle = "30mm x 30mm";
        this.exitWidth = 3 * 28;
      } else if (this.formSize.size === "3") {
        // this.exitTitle = "40mm x 40mm";
        this.exitWidth = 4 * 28;
      } else if (this.formSize.size === "4") {
        // this.exitTitle = "50mm x 50mm";
        this.exitWidth = 5 * 28;
      } else if (this.formSize.custom) {
        if (this.formSize.custom >= 1 && this.formSize.custom <= 35) {
          this.exitWidth = this.formSize.custom * 28;
        } else {
          this.formSize.custom = "";
          this.$message.error("1cm ≤ 二维码大小 ≥ 35cm");
          return false;
        }
      }
    },
    //删除
    handleDelete(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.Sevice({
            url: "product/delete",
            method: "post",
            data: ids,
          })
            .then((res) => {
              if (res && res.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.$refs.dataTable.clearSelection();
                this.getUserlist();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleProjectDriverI(id) {
      var ids = this.dataProjectDriverI.map((item) => {
        return { id: item.id };
      });
      console.log(ids);
      this.updateProjectesVisible = true;
      this.$nextTick(() => {
        this.$refs.updateProjectes.init(ids);
      });
    },
    handleProjectDriver(id) {
      this.updateProjectVisible = true;
      this.$nextTick(() => {
        this.$refs.updateProject.init(id);
      });
    },
    handleLook(id) {
      this.lookVisible = true;
      this.$nextTick(() => {
        this.$refs.look.init(id);
      });
    },
    handleActivation(id) {
      this.activationVisible = true;
      this.$nextTick(() => {
        this.$refs.activation.init(id);
      });
    },
    // qrBack(dataUrl){
    //   console.log(dataUrl)
    // },
    handleQrcode(id, code) {
      (this.formSize = {
        size: "2",
        custom: 2,
      }),
        (this.exitWidth = 84);
      this.codeQr = code;
      this.codeText = "https://a.xdjnbyq.com/wxapp?id=" + id;
      this.qrcodeDialogVisible = true;
    },
    // url 二维码内容链接 size 二维码大小（高宽） qrText 底部描述文字 color 二维码颜色

    async initCanvas(url, size, qrText, color = "#000") {
      const canvas = await QRCode.toCanvas(url, {
        errorCorrectionLevel: "H",
        margin: 1, // 设置padding 二维码的padding
        height: size,
        width: size,
        scal: 177,
        color: { dark: color },
        rendererOpts: { quality: 0.9 },
      });
      const fontWeight = "bold"; // 字体 粗体 格式
      const fontSize = 14; // 字体大小
      const tb = 5; // 底部文字上下间距
      const realHeight = size + fontSize + 2 * tb; //实际高度
      // 画布上下文对象
      const ctx = canvas.getContext("2d");
      // 获取二维码数据
      const data = ctx.getImageData(0, 0, size, size);
      ctx.fillStyle = "#fff";
      canvas.setAttribute("height", realHeight); // 重设画布像素高度
      canvas.style.setProperty("height", realHeight + "px"); // 重设画布实际高度
      ctx.fillRect(0, 0, size, realHeight);
      ctx.putImageData(data, 0, 0); // 填充二维码数据
      ctx.font = `${fontWeight} ${fontSize}px Arial`;
      const textWidth = ctx.measureText(qrText).width; //文字真实宽度
      const ftop = size + tb; //文字距顶部位置
      const fleft = (size - textWidth) / 2; //根据字体大小计算文字left
      const textPadding = fontSize / 2; //字体边距为字体大小的一半可以自己设置
      // 设置底部背景色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, size, size, realHeight - 2 * tb);
      // 设置字体填充位置
      ctx.fillRect(
        fleft - textPadding / 2,
        ftop - textPadding / 2,
        textWidth + textPadding,
        fontSize + textPadding
      );
      ctx.textBaseline = "top"; //设置绘制文本时的文本基线。
      ctx.fillStyle = "#333"; // 字体颜色
      ctx.fillText(qrText, fleft, ftop);
      console.log(canvas.toDataURL());
      return canvas;
    },

    createQRCode(url, size, codeQr, num) {
      let qrText = codeQr; //底部文字
      let topText = ""; //顶部文字
      let qrUrl = url; //url，二维码内容，或跳转链接
      // let qrcode_canvas = this.$refs.qrcode_canvas;
      // let qrcode_logo = this.$refs.qrcode_logo;
      const qrcode_canvas = new Image();
      let canvas = this.$refs.canvas;
      const that = this;
      QRCode.toDataURL(
        qrUrl,
        { errorCorrectionLevel: "H", margin: 1 },
        (err, url) => {
          qrcode_canvas.src = url;
          // 画二维码里的logo// 在canvas里进行拼接
          let ctx = canvas.getContext("2d");
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.beginPath(); //创建一个路径
          ctx.roundRect(0, 0, size, size, 5);
          ctx.lineWidth = 1;
          ctx.strokeStyle = "#000";
          ctx.fillStyle = "#fff";
          ctx.fill();
          ctx.stroke(); //渲染直线(描边)
          setTimeout(() => {
            //使用setTimeout变为异步
            //获取图片
            // ctx.rect(0.5 * (size - size-12), 0.5 * (size - size-12), ...[size-12,size-12]);
            if (qrText && num == 2) {
              //设置字体
              let fpadd = 5; //规定内间距
              ctx.font = "bold " + 10 + "px Arial";
              let tw = ctx.measureText(qrText).width; //文字真实宽度
              let ftop = size - 12; //根据字体大小计算文字top
              let fleft = (size - tw) / 2; //根据字体大小计算文字left
              let tp = 12 / 2; //字体边距为字体大小的一半
              ctx.fillStyle = "transparent";
              ctx.fillRect(fleft - tp / 2, ftop - tp / 2, tw + tp, 12 + tp);
              ctx.textBaseline = "top"; //绘制文本时的文本基线
              ctx.fillStyle = "#333";
              ctx.fillText(qrText, fleft, ftop); //canvas填充文字
              ctx.drawImage(qrcode_canvas, 7.5, 2, size - 15, size - 15);
            } else {
              ctx.drawImage(qrcode_canvas, 0, 0, size, size);
            }

            qrcode_canvas.src = canvas.toDataURL();
            this.downloadQRCode(qrcode_canvas, codeQr);
          }, 0);
        }
      );
    },
    downloadQRCode(image, name) {
      let imgUrl = "";
      let img = image;
      img.onload = function () {
        imgUrl = img.getAttribute("src");
        let link = document.createElement("a");
        link.setAttribute("href", imgUrl);
        link.setAttribute("download", name + ".png");
        link.click();
      };
    },
    qrcodeClick(num) {
      // let canvas=this.initCanvas(this.codeText,this.exitWidth,this.codeQr)
      // console.log(canvas)
      this.createQRCode(this.codeText, this.exitWidth, this.codeQr, num);

      // let Qrcode = this.$refs.qrcode2
      // console.log(Qrcode)
      // const a = document.createElement('a');
      // a.href = Qrcode.$el.currentSrc;
      // // a.href = canvas.toDataURL();
      // a.setAttribute('download', this.codeQr);
      // a.click();
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserlist();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getUserlist();
    },
  },
};
</script>

<style scoped>
.imglist {
  display: block;
  margin: 10px;
  width: 180px;
  height: 180px;
}

.goodsindex {
  width: 100%;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
}

/* 搜索 */
.goodsindex-queryInfo {
  margin-bottom: 10px;
}

.goodsindex-queryInfo-li {
  width: 100%;
  height: auto;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 列表 */
.goodsindex-list {
  width: 100%;
  height: auto;
  margin-top: 20px;
}

/* 分页 */
.goodsindex-page-box {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: flex-end;
}

/* 预览 */
/* /deep/.el-dialog__body{
    padding: 0;
    padding-bottom: 20px;
}
/deep/.el-dialog__header{
    height: 0px;
    padding: 0;
}
/deep/.el-dialog__headerbtn{
    position: absolute;
    top: 20px;
}
/deep/.el-dialog__headerbtn i{
    color: #fff;
} */
/deep/ .el-tree-node__label {
  white-space: normal;
  word-break: break-all;
}

/deep/ .el-tree-node__content {
  height: auto;
}

/* .treeOverflow::-webkit-scrollbar {
  display: none;
  width: 0 !important;
} */
.treeOverflow::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
}

.treeOverflow::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px #c1c1c1;
  background: #c1c1c1;
}

.treeOverflow::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #f1f1f1;
  border-radius: 0;
  background: #f1f1f1;
}

.qrcodesize {
  width: 0px;
  height: 0px;
  overflow: auto;
}
.canvas {
  background: red;
}
</style>
